//
//  ShareAlert.swift
//  CheckmeRing
//
//  Created by 董鹏 on 2022/2/27.
//

import UIKit
import SVProgressHUD

class ShareAlert: UIView {

    @IBOutlet weak var bgView: UIView!
    @IBOutlet weak var csvBtn: UIButton!
    @IBOutlet weak var pdfBtn: UIButton!
    @IBOutlet weak var cloudBtn: UIButton!
    
    /// 分享的数据(字典)
    var passData = [[String: Any]]()
    /// 分享的数据(模型)
    var historyData = [RModel]()
    /// 存储的key
    var timeStamp = String()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
            self.setUI()
        }
    }
    
    func setUI(){
        
        self.bgView.maskCorners(corners: UIRectCorner.init(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue), cornerRadi: 20)
        csvBtn.layer.borderColor = hexColor("E8E8E8")?.cgColor
        pdfBtn.layer.borderColor = hexColor("E8E8E8")?.cgColor
        cloudBtn.layer.borderColor = hexColor("E8E8E8")?.cgColor
        
        self.isUserInteractionEnabled = true
        let ges = UITapGestureRecognizer.init(target: self, action: #selector(cancelBtnDidClicked(_:)))
        self.addGestureRecognizer(ges)
    }
    
    @IBAction func shareAsCSV(_ sender: UIButton) {
        self.setBtnSelect(sender)
        let vc = SimpleWebViewController.init()
        vc.shareURL = URL.init(fileURLWithPath: SaveObject.save(toLocal: passData))
        vc.isShare = true
        vc.hidesBottomBarWhenPushed = true
        getCurrentViewController()?.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func shareAsPDF(_ sender: UIButton) {
        self.setBtnSelect(sender)
        self.initPDF()
    }
    
    @IBAction func CloudUpload(_ sender: UIButton) {
        
        if CacheManager.manager.containsObject(forKey: HistoryUploadConfig) == false {
            self.showYCToast(message: "クラウド情報が未入力です。")
            return
        }
        
        if historyData.first?.hadUpload == true {
            self.showYCToast(message: "アップロード済み")
            return
        }
        
        // 已上传更新
        for model in self.historyData {
            model.hadUpload = true
        }
        CacheManager.manager.setValueForKey(self.timeStamp, self.historyData as NSCoding)
        
        NotificationCenter.default.removeObserver(self)
        NotificationCenter.default.addObserver(self, selector: #selector(uploadFinshFunction), name: NSNotification.Name.init(rawValue: UploadState), object: nil)
        
        self.setBtnSelect(sender)
        SVProgressHUD.show()
        // 上传历史数据
        RManager.manager.needUpdateData.append(contentsOf: self.historyData)
        RManager.manager.uploadHistoryListToCloud(isHistory: true)
        
    }
    
    func setBtnSelect(_ sender: UIButton) {
        sender.layer.borderColor = hexColor("3468E2")!.cgColor
        sender.setTitleColor(hexColor("3468E2"), for: .normal)
        
        if sender == self.cloudBtn {
            return
        }
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            self.removeFromSuperview()
        }
    }
    
    @IBAction func cancelBtnDidClicked(_ sender: Any) {
        SVProgressHUD.dismiss()
        self.removeFromSuperview()
    }
    
    @objc func uploadFinshFunction() {
        SVProgressHUD.dismiss()
        self.removeFromSuperview()
    }
    
}

extension ShareAlert {
    
    func initPDF() {
        let A4paperSize = CGSize(width: 520, height: 830)
        let pdf = SimplePDF(pageSize: A4paperSize)
        
        guard let view = Bundle.main.loadNibNamed("SharePDF", owner: nil, options: nil)?.first as? SharePDF else {
            print("通过Xib加载失败")
            return
        }
        view.setData(list: self.historyData)
        pdf.addImage(view.changeToImage(size: A4paperSize))
        pdf.setContentAlignment(.center)
        let pdfData = pdf.generatePDFdata()

        // save as a local file
        let basePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).map(\.path).last!
        let filePath = URL(fileURLWithPath: basePath).appendingPathComponent(String(format: "CheckmeRing_%@.pdf", formatTimeStamp(time: historyData.first!.timeStamp, format: "yyyyMMddHHmmss"))).path
        print("filePath=\(filePath)")
        let path = URL(fileURLWithPath: filePath)
        try! pdfData.write(to: path, options: .atomic)
        
        let vc = SimpleWebViewController.init()
        vc.shareURL = path
        vc.isShare = true
        vc.hidesBottomBarWhenPushed = true
        getCurrentViewController()?.navigationController?.pushViewController(vc, animated: true)
        
    }
    
}
